﻿/*
	Class			Screen
	
	Description		Takes a given BitmapData and redraws it with pixels created using the Pixel class.
					It is then scaled to original size or larger to finish the effect.
					
	History			1.03	6/18/07		Changed all uints to ints.
					1.02	6/06/07		Source can now also be a BitmapData object.
					1.01	5/29/07		Included draw bitmapdata in the Constructor.
					1.00	5/26/07		Created
	
	To Do			n/a
*/

package tv.digitalfx
{
	import tv.digitalfx.Pixel;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Point;
	
	public class Screen extends Sprite
	{
		private var pixelWidth:int;
		private var finalScale:Number;
		private var sourceObject:*;
		private var sourceWidth:int;
		private var sourceHeight:int;
		private var sourceBMD:BitmapData;
		
		
		public function Screen (src:*, fScale:Number = 3, pWidth:int = 3)
		{
			pixelWidth   = pWidth;
			finalScale   = fScale;
			sourceWidth  = src.width;
			sourceHeight = src.height;
			
			if (src is BitmapData)
			{
				sourceBMD = src;
			}
			else
			{
				sourceObject = src;
				sourceBMD    = new BitmapData (sourceWidth, sourceHeight, true, 0x00FFFFFF);
				sourceBMD.draw (sourceObject);
			}
			
			drawScreen ();
		}
		
		
		private function drawScreen ():void
		{
			var col:int      = 0;
			var row:int      = 0;
			var origin:Point = new Point ();
			
			for (row = 0; row < sourceHeight; row++)
			{
				origin.x = 0;
				
				for (col = 0; col < sourceWidth; col++)
				{
					var pixelValue:int = sourceBMD.getPixel32 (col, row);
					var alphaHex:int   = pixelValue >> 24 & 0xff;
					
					if (alphaHex > 0)
					{ 
						var pixel:Pixel = new Pixel (pixelValue, pixelWidth, false); // (color:int, pixelSquareSize:int, gapOn:Boolean, gapSize:int)
						pixel.x         = origin.x;
						pixel.y         = origin.y;
						
						this.addChild (pixel);
					}
					
					origin.offset (pixelWidth, 0);
				}
				
				origin.offset (0, pixelWidth);
			}
			
			sourceBMD.dispose ();
			
			this.cacheAsBitmap				= true;
			this.scaleX = this.scaleY		= (1 / pixelWidth) * finalScale;
			
			
			if (sourceObject != undefined && sourceObject.parent)
				sourceObject.parent.removeChild (sourceObject);
				
		}
		
		
	}
}